# This is a sample Python script.
import sys

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import xmindparser
import xlwt
import testcase
import csv


def Transfer(file, output):
    # Use a breakpoint in the code line below to debug your script.
    testcases = xmindparser.xmind_to_dict(file)[0]['topic']
    workbook = xlwt.Workbook(encoding='UTF-8')
    worksheet = workbook.add_sheet(testcases['title'], cell_overwrite_ok=True)
    row0 = ['Test Case Identifier', 'Priority', 'Summary', 'Pre-Conditions', 'Data', 'Action', 'Expected Result',
            'Labels', 'Test Repository Path']
    for i in range(len(row0)):
        worksheet.write(0, i, row0[i])

    lst = []
    r_s = testcases['title']
    process_dict(testcases, r_s, lst)
    dct = {}
    tc_lst = process_list(lst, dct, worksheet)
    dump_tc_lst(tc_lst, worksheet)
    workbook.save(output)


def process_dict(root, rootstring, list_container):
    # print('start list')
    # print( list_container)
    if isinstance(root, dict):
        if len(root) >= 2 and 'topics' in root.keys():
            process_dict(root['topics'], str(rootstring), list_container)
        if len(root) == 1:
            process_dict(root['title'], str(rootstring), list_container)

    elif isinstance(root, list):
        for dec_root in root:
            process_dict(dec_root, str(rootstring) + "###" + dec_root['title'], list_container)

    elif isinstance(root, str):
        list_container.append(str(rootstring))


def process_list(lst, content: list, worksheet):
    tc_list = []
    for rec in lst:
        rec = rec.replace('：', ':')
        tc = testcase.test_case()
        parts = rec.split('###')
        repositorypath = ''
        for i in range(len(parts)):
            if parts[i].startswith('tc'):
                break
            else:
                repositorypath = repositorypath + '/' + parts[i]
        for seg in parts:
            if 'tc' in seg:
                title = seg.split(':')[1]
                idx = check(tc_list, title)
                if idx == -1:
                    tc.title = title
                    tc.repositoryPath = repositorypath
                    tc_list.append(tc)
                else:
                    tc = tc_list[idx]
                i = parts.index(seg)
                if len(parts) - i > 1:
                    step = parts[i + 1]
                    if 'pc' in step:
                        condition = step.split(':')[1]
                        tc.condition = condition
                    else:
                        #添加步骤step
                        tst_step = testcase.test_step()
                        tst_step.title = step
                        exp = ' '
                        if len(parts) - i > 3:
                            exp = parts[i + 2]
                            data = parts[i + 3]
                            tst_step.dataed.append(data)
                            # tst_step.expected.append(exp)
                            # tc.apptend_step(tst_step)
                        elif len(parts) - i > 2:
                            # print('else')
                            exp = parts[i + 2]
                        #添加预期结果
                        tst_step.expected.append(exp)
                        tc.apptend_step(tst_step)

    return tc_list


def dump_tc_lst(tc_lst, worksheet):
    l = 1
    for tc in tc_lst:
        idx = tc_lst.index(tc) + 1
        worksheet.write(l, 1, priority)
        worksheet.write(l, 2, tc.title)
        worksheet.write(l, 3, tc.condition)

        worksheet.write(l, 7, label1)
        worksheet.write(l, 8, tc.repositoryPath)
        # worksheet.write(l, 8,state)
        data_str = ''
        exp_str = ''
        for step in tc.steps:
            worksheet.write(l, 0, idx)
            worksheet.write(l, 5, step.title)
            for exp in step.expected:
                if exp_str == '':
                    exp_str = str(exp)
                else:
                    exp_str = exp_str + '; ' + str(exp)
            worksheet.write(l, 6, exp_str)
            exp_str = ''
            for data in step.dataed:
                if data_str == '':
                    data_str = str(data)
                else:
                    data_str = data_str + '; ' + str(data)
            worksheet.write(l, 4, data_str)
            data_str = ''
            l = l + 1


def check(lst, title):
    for case in lst:
        if case.title == title:
            return lst.index(case)
    return -1



if __name__ == '__main__':
    priority='Medium'
    # label1='建模管理'
    label1=''
    # assign_to=''
    # state='Design'

    # file_name = "C:\\work\\xmind\\2024上半年\\四个低压母线\\去除低压来源"
    if len(sys.argv) < 1:
        print("请至少提供一个参数。")
        sys.exit(1)
    file_name = sys.argv[1][:-6]
    print(file_name)
    xmind_file = file_name + '.xmind'
    exl_output = file_name +'.xls'
    csv_output = file_name + '.csv'
    Transfer(xmind_file,exl_output)

# Press the green button in the gutter to run the script.
# if __name__ == '__main__':
    # priority = 'Medium'
    # # label1='建模管理'
    # label1 = ''
    # # assign_to=''
    # # state='Design'
    # file_name = "C:\\work\\测试Xmind导图\\2024年上半年\\去除低压来源"
    # xmind_file = file_name + '.xmind'
    # csv_output = file_name +'.xls'
    # Transfer(xmind_file, csv_output)


# See PyCharm help at https://www.jetbrains.com/help/pycharm/
